package com.kqb.service.impl;


import com.kqb.common.domain.AjaxResult;
import com.kqb.mapper.DictMapper;
import com.kqb.pojo.Department;
import com.kqb.pojo.Dict;
import com.kqb.pojo.vo.DictVo;
import com.kqb.service.IDictService;
import com.kqb.utils.ThreadLocalUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 杉果树皮
 * @date 2025/2/23 17:23
 * @description:
 */
@Service
public class DictServiceImpl implements IDictService {
    @Autowired
    private DictMapper dictMapper;

    @Override
    public AjaxResult save(Dict dict) {
        dict.setCreatedBy((String) ThreadLocalUtils.getThreadLocalUtils().getCurrentUser().get("account"));
        return dictMapper.selectByName(dict.getName()) == 0 ? (dictMapper.save(dict) == 0 ? AjaxResult.error("添加分类失败") : AjaxResult.success("添加分类成功")) : AjaxResult.error("此分类已存在，添加失败");

    }

    @Override
    public AjaxResult selectAll() {
        List<Dict> dicts = dictMapper.selectByPid(0);
        ArrayList<DictVo> dictVos = new ArrayList<>();
        for (Dict dict : dicts) {
            DictVo dictVo = new DictVo();
            ArrayList<Dict> dicts1 = (ArrayList<Dict>) dictMapper.selectByPid(dict.getId());
            BeanUtils.copyProperties(dict, dictVo);
            dictVo.setTableData(dicts1);
            dictVos.add(dictVo);
        }
        return AjaxResult.success("查询所有分类成功", dictVos);
    }

    @Override
    public AjaxResult deleteById(Integer id) {
        if (dictMapper.selectByParentId(id) != 0) {
            return AjaxResult.error("存在子字典，不允许删除");
        }
        return dictMapper.delete(id) == 0 ? AjaxResult.error("删除字典失败") : AjaxResult.success("删除字典成功");
    }

    @Override
    public AjaxResult update(Dict dict) {
        Dict select = dictMapper.select(dict.getId());
        if (select == null) {
            return AjaxResult.error("修改失败，没有对应的字典");
        }
        return dictMapper.update(dict) == 0 ? AjaxResult.error("修改字典失败") : AjaxResult.success("修改字典成功");
    }

    @Override
    public AjaxResult selectByCode(String code) {
        List<Dict> dicts = dictMapper.selectByCode(code);
        DictVo dictVo = new DictVo();
        ArrayList<Dict> subDict = new ArrayList<>();
        dicts.forEach((dict -> {
            if (dict.getPid() == 0) {
                BeanUtils.copyProperties(dict, dictVo);
            } else {
                subDict.add(dict);
            }
        }));
        dictVo.setSubDict(subDict);
        return AjaxResult.success("查询字典成功", dictVo);
    }
}
